package com.juku2024.juku

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.wanban.adutils.utils.OpenAdTools
import com.wanban.adutils.utils.ReopenAdTools
import com.wanban.adutils.utils.VideoInterstitialAdTools
import com.juku2024.juku.adapter.HomeBottomFragmentAdapter
import com.juku2024.juku.base.BaseActivity
import com.juku2024.juku.dialog.NoticeDialog
import com.juku2024.juku.model.MainRestartEvent
import com.juku2024.juku.model.Notice
import com.juku2024.juku.tools.*
import com.juku2024.juku.viewmodel.MainViewModel
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus


class MainActivity : BaseActivity() {

    private var news = -1
    // 返回双击
    private var exitDisposable: Disposable? = null
    private val communityAdapter by lazy { HomeBottomFragmentAdapter(this) }
    private val viewModel by lazy { getViewModel(MainViewModel::class.java) }

    private lateinit var viewPager: ViewPager2
    private lateinit var tabLayout: TabLayout
    private lateinit var layoutNotify: View

    override fun getLayoutResId(): Int {
        return R.layout.activity_main
    }
    

    override fun initView() {
        super.initView()
        viewPager = findViewById(R.id.viewPager)
        tabLayout = findViewById(R.id.tabLayout)
        layoutNotify = findViewById(R.id.layoutNotify)


        viewPager.orientation = ViewPager2.ORIENTATION_HORIZONTAL
        viewPager.isUserInputEnabled = false
        viewPager.offscreenPageLimit = 5
        // 绑定adapter
        viewPager.adapter = communityAdapter
        TabLayoutMediator(tabLayout, viewPager, true) { tab, position ->
            tab.setCustomView(R.layout.layout_bottom_tab)
            val tvTab = tab.customView?.findViewById<TextView>(R.id.tvTab)
            tvTab?.text = communityAdapter.tabNames[position]
            val ivTab = tab.customView?.findViewById<ImageView>(R.id.ivTabIcon)
            val resId = when (position) {
                0 -> R.drawable.selector_home_tab_icon_0
                1 -> R.drawable.selector_home_tab_icon_1
                2 -> R.drawable.selector_home_tab_icon_2
                3 -> R.drawable.selector_home_tab_icon_3
                4 -> R.drawable.selector_home_tab_icon_4
                else -> 0
            }
            ivTab?.setBackgroundResource(resId)
        }.attach()
    }

    override fun bindEvent() {
        super.bindEvent()
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.position?.let { viewPager.setCurrentItem(it, false) }
            }

        })
        layoutNotify.setOnClickListener {
            SPUtil.instance.notifySystemId = news
            layoutNotify.visibility = View.GONE
            val intent = Intent(this, FeedbackActivity::class.java)
            startActivity(intent)
        }
    }

    override fun init(savedInstanceState: Bundle?) {
        // 注册ReopenAd
        ReopenAdTools.init(this)

        if (!VideoInterstitialAdTools.isAdLoadSuccess()) {
            VideoInterstitialAdTools.loadAd(this)
        }

        viewModel.hasNewSystemMsg {
            if (isActivityNotActive()) return@hasNewSystemMsg
            if (!it) return@hasNewSystemMsg
            // 有新的系统消息
            layoutNotify.visibility = View.VISIBLE
        }
        getAAID()
    }

    override fun onResume() {
        super.onResume()
        // 加载开屏广告
        if (OpenAdTools.isAdLoadSuccess()) {
            OpenAdTools.showAd(this)
        }
    }

    fun initNotify(news: Int) {
        // 如果查询新消息发现有新的反馈, 不在处理
        if (layoutNotify.visibility == View.VISIBLE) {
            return
        }
        if (news >= 0) {
            val localNewsId = SPUtil.instance.notifySystemId
            if (news > localNewsId) {
                this.news = news
                layoutNotify.visibility = View.VISIBLE
            } else {
                layoutNotify.visibility = View.GONE
            }
        } else {
            layoutNotify.visibility = View.GONE
        }
    }


    fun showNotifyDialog(notice: Notice?){
        NoticeDialog.showNotifyDialog(this, notice)
    }
    @Suppress("DEPRECATION")
    @Deprecated("Deprecated in Java")
    override fun onBackPressed() {
        if (exitDisposable == null || exitDisposable?.isDisposed == true) {
            AlertUtils.alert("再按一次退出程序")
            exitDisposable = RxUtils.delay(2500L) {}
        } else {
            super.onBackPressed()
            if (exitDisposable != null) {
                exitDisposable?.dispose()
                exitDisposable = null
            }
        }
    }

    override fun onRestart() {
        super.onRestart()
        EventBus.getDefault().post(MainRestartEvent())
    }

    fun getAAID() {
//        if (BuildConfig.DEBUG) {
////            RxUtils.doObservable<String?> {
////                val aaid = AdvertisingIdClient.getAdvertisingIdInfo(BaseApplication.context).id
////                LogC.e("aaid -> $aaid")
////                it.onComplete()
////            }
////            FirebaseMessaging.getInstance().token.addOnCompleteListener(OnCompleteListener { task ->
////                if (!task.isSuccessful) {
////                    LogC.e("token -> Fetching FCM registration token failed " + task.exception)
////                    return@OnCompleteListener
////                }
////
////                // Get new FCM registration token
////                val token = task.result
////                LogC.e("token -> $token")
////                DialogUtils.showAlertDialog(this, "firebaseToken", "token -> $token", "复制", {
////                    //获取剪贴板管理器：
////                    val cm: ClipboardManager = this.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
////                    // 创建普通字符型ClipData
////                    val mClipData = ClipData.newPlainText("FirebaseToken", token)
////                    // 将ClipData内容放到系统剪贴板里。
////                    cm.setPrimaryClip(mClipData)
////                }, "取消", {})
////            })
//        }
    }

}